import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import config from '@/config.js';

export const useTerminalStore = defineStore('terminal', {
  state: () => ({
    conn: null,
    history: [], // 存储终端历史记录（仅数据，不包含 socket 实例）
    isConnected: false,
  }),
  actions: {
    // 建立或复用连接（跨路由保活）
    connect(conn) {
      if (this.socket && this.socket.connected) {
        if (conn) this.conn = conn;
        return;
      }
      this.conn = conn || this.conn;
      if (!this.conn) return;

      if (!this._onDataSubs) this._onDataSubs = [];

      const { host, port = 22, username, password } = this.conn;
      this.socket = io(`http://${config.socket.host}:${config.socket.port}/ws/ssh`, { transports: ['websocket'] });

      this.socket.on('connect', () => {
        this.isConnected = true;
        this.socket.emit('start', { host, port, username, password });
      });

      this.socket.on('data', (data) => {
        // 写入输出历史
        this.history.push({ type: 'output', content: data, timestamp: new Date().toISOString() });
        // 通知订阅者（用于 UI 写入）
        this._onDataSubs.forEach(fn => { try { fn(data); } catch (_) {} });
      });

      this.socket.on('disconnect', () => {
        this.isConnected = false;
      });

      this.socket.on('connect_error', (error) => {
        this.history.push({ type: 'system', content: `连接错误: ${error.message}`, timestamp: new Date().toISOString() });
        this.isConnected = false;
      });
    },

    // 发送输入到后端，并记录输入历史
    sendInput(data) {
      if (this.socket && this.socket.connected) {
        this.socket.emit('input', data);
        this.history.push({ type: 'input', content: data, timestamp: new Date().toISOString() });
      }
    },

    // 订阅实时输出（返回取消订阅函数）
    subscribeOnData(fn) {
      if (!this._onDataSubs) this._onDataSubs = [];
      this._onDataSubs.push(fn);
      return () => {
        this._onDataSubs = this._onDataSubs.filter(f => f !== fn);
      };
    },

    addToHistory(record) {
      this.history.push(record);
    },

    clearHistory() {
      this.history = [];
    },

    disconnect() {
      if (this.socket) {
        this.socket.disconnect();
        this.socket = null;
        this.isConnected = false;
      }
    }
  },
  // 仅持久化可序列化数据，排除 socket/订阅者
  persist: {
    paths: ['conn', 'history', 'isConnected']
  }
});